import tkinter as tk
from tkinter import ttk

class NiceButton(tk.Canvas):
    def __init__(self, master=None, text="Button", bg_color="#4CAF50", fg_color="white", 
                 hover_color="#45a049", corner_radius=10, command=None, **kwargs):
        super().__init__(master, **kwargs)
        self.command = command
        self.bg_color = bg_color
        self.fg_color = fg_color
        self.hover_color = hover_color
        self.corner_radius = corner_radius
        self.text = text

        # 绑定事件
        self.bind("<Enter>", self.on_enter)
        self.bind("<Leave>", self.on_leave)
        self.bind("<Button-1>", self.on_click)

        # 绘制按钮
        self.draw_button()

    def draw_button(self):
        self.delete("all")  # 清除画布内容
        width = self.winfo_reqwidth()
        height = self.winfo_reqheight()

        # 绘制圆角矩形背景
        self.create_round_rect(0, 0, width, height, radius=self.corner_radius, fill=self.bg_color)

        # 添加文字
        # self.create_text(width // 2, height // 2, text=self.text, fill=self.fg_color, font=("Arial", 12))
        self.create_text(width // 2, height // 2, text=self.text, fill=self.fg_color)

    def create_round_rect(self, x1, y1, x2, y2, radius=10, **kwargs):
        """绘制圆角矩形"""
        points = [
            x1 + radius, y1,
            x2 - radius, y1,
            x2, y1,
            x2, y1 + radius,
            x2, y2 - radius,
            x2, y2,
            x2 - radius, y2,
            x1 + radius, y2,
            x1, y2,
            x1, y2 - radius,
            x1, y1 + radius,
            x1, y1,
        ]
        return self.create_polygon(points, **kwargs, smooth=True)

    def on_enter(self, event):
        """鼠标悬停时改变背景颜色"""
        self.draw_button()
        self.create_round_rect(0, 0, self.winfo_reqwidth(), self.winfo_reqheight(), 
                               radius=self.corner_radius, fill=self.hover_color)
        self.create_text(self.winfo_reqwidth() // 2, self.winfo_reqheight() // 2, 
                        #  text=self.text, fill=self.fg_color, font=("Arial", 12))
                         text=self.text, fill=self.fg_color)

    def on_leave(self, event):
        """鼠标离开时恢复背景颜色"""
        self.draw_button()

    def on_click(self, event):
        """点击按钮时执行命令"""
        if self.command:
            self.command()

# 测试代码
if __name__ == "__main__":
    root = tk.Tk()
    root.title("Nice Button Example")
    root.geometry("300x200")

    def button_click():
        print("Nice Button Clicked!")

    # 创建自定义按钮
    nice_button = NiceButton(root, text="Click Me", bg_color="#4CAF50", fg_color="white", 
                             hover_color="#45a049", corner_radius=10, command=button_click, 
                             width=100, height=40)
    nice_button.pack(pady=50)

    root.mainloop()